package com.epam.cdp.ejb.async;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.Future;

import javax.annotation.Resource;
import javax.ejb.AsyncResult;
import javax.ejb.Asynchronous;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@Stateless
public class AsyncBean {
	private final static Log log = LogFactory.getLog(AsyncBean.class);
	
	@Resource
	private SessionContext sessionContext;
	
	@Asynchronous
	public void veryLongOperation() {
		log.info("Starting...");
		try {
			Thread.sleep(20000);
		} catch (InterruptedException e) {
			log.error("Failed to sleep thread", e);
		}
		log.info("Finished");
	}
	
	
	@Asynchronous
	public Future<String> getString() {
		Random random = new Random(new Date().getTime());
		int sleepTime = 1000 * random.nextInt(10);
		AsyncResult<String> result = null;
		try {
			Thread.sleep(sleepTime);
		} catch (InterruptedException e) {
			log.error("Failed to sleep thread", e);
		}
		if (!sessionContext.wasCancelCalled()) {
			result = new AsyncResult<String>("Processing finished after " + sleepTime + " miliseconds");
			
		}
		log.debug("Returting " + result + " after " + sleepTime + " miliseconds");
		return result;
	}
}
